package com.example.peanutsubway.web;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * @Author：liulei
 * @Version：1.0
 * @Date：2021/10/12-16:27
 * @Since:jdk1.8
 * @Description:
 */
@WebServlet("/fileUpdateLoad.do")
public class FileUpdateLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String fileName = "";
        // 1.获取上传的文件的路径
        String realPath = this.getServletContext().getRealPath("/");// 获取项目发布的根目录（带盘符）
        System.out.println(realPath);
        // 1.1 获取文件上传的路径
        File file = new File(realPath + "//upload");
        // 1.2 判断文件夹是否存在，如果不存在，就创建
        if (!file.exists()) {
            file.mkdir();
        }
        // 2.验证文件上传的表单元素的格式是否正确(method=post、enctype=multipart/form-data)
        // 2.1 实例化文件工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        // 2.2 实例化ServletFileUpload对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        // 2.3 验证表单是否符号要求
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // 3.上传文件
                // 3.1 将HttpServletRquest对象转为List<FileItem>
                List<FileItem> list = servletFileUpload.parseRequest(request);

                String fileType = "";
                // 3.2 遍历list集合
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        // 获取表单元素的name值
                        String fieldName = fileItem.getFieldName();
                        if (fieldName.equals("type")) { // 上传的文件存储的文件类型(不同表上传的文件存放在不同的文件中)
                            fileType = fileItem.getString();
                        }
                    }
                }
                for (FileItem fileItem : list) {
                    if (!fileItem.isFormField()) {// 要上传的文件字段
                        // 3.3 新建文件
                        // 文件路径
                        String filePath = realPath + "//upload//" + fileType + "//";
                        File typeFile = new File(filePath);
                        if (!typeFile.exists()) {
                            typeFile.mkdirs();
                        }
                        fileName = new Date().getTime() + fileItem.getName();
                        // 文件名
                        String fileNamePath = filePath + new Date().getTime() + fileItem.getName();
                        File newFile = new File(fileNamePath);
                        // 创建文件
                        fileItem.write(newFile);
                    }
                }
                PrintWriter out = response.getWriter();
                out.write(fileName);
                out.flush();
                out.close();
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
